package secondriver.heathfood.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import butterknife.Bind;
import butterknife.ButterKnife;
import secondriver.heathfood.HeathFoodApplication;
import secondriver.heathfood.R;
import secondriver.heathfood.adapter.ViewPagerAdapter;
import secondriver.heathfood.client.ApiClient;
import secondriver.heathfood.client.Constants;
import secondriver.heathfood.common.*;

import java.util.ArrayList;

/**
 * Author : secondriver
 */
public class HomeActivity extends AbstractBaseActivity {

    final static int LoadingWhat = 0x01;
    final static int DialogWhat = 0x10;

    private ProgressDialog mProgressDialog;
    private int mProgressValue = 0;
    private int mMaxProgressValue = 100;

    private Handler mHandler;
    private ApiClient mApiClient;

    private static final int[] pics = {
            R.drawable.welcome_vp_0,
            R.drawable.welcome_vp_1,
            R.drawable.welcome_vp_2,
            R.drawable.welcome_vp_3,
    };

    @Bind(R.id.view_pager)
    ViewPager mViewPager;
    @Bind(R.id.point_line)
    LinearLayout pointLinearLayout;


    private ViewPagerAdapter mViewPagerAdapter;
    private ArrayList<View> mViews;

    private ImageView[] mPointViews;
    private int currentIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_home);

        ButterKnife.bind(this);

        initVariable();
        initPagerView();
        initPageViewData();
        initPointViewData();
    }


    private void initVariable() {

        mApiClient = ApiClient.build(this, Constants.FOOD_CLASS_CACHE_NAME);

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case DialogWhat:
                        if (mProgressValue > mMaxProgressValue) {
                            mProgressValue = 0;
                            mProgressDialog.setProgress(mProgressValue);
                        } else {
                            mProgressDialog.incrementProgressBy(1);
                        }
                        sendEmptyMessageDelayed(DialogWhat, 100);
                        break;
                    case LoadingWhat:
                        if (mProgressDialog.isShowing()) {
                            mProgressDialog.dismiss();
                        }
                        Intent intent = new Intent(HomeActivity.this, FoodClassActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra(Constants.FOOD_CLASS_CONTENT_KEY, (String) msg.obj);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        };
    }


    private void initPointViewData() {
        mPointViews = new ImageView[pics.length];
        for (int i = 0, s = pics.length; i < s; i++) {
            mPointViews[i] = (ImageView) pointLinearLayout.getChildAt(i);
            mPointViews[i].setEnabled(true);
            mPointViews[i].setOnClickListener(pointImageViewOnClickHandler);
            mPointViews[i].setTag(i);
        }
        currentIndex = 0;
        mPointViews[currentIndex].setEnabled(false);
    }

    private void initPageViewData() {
        LinearLayout.LayoutParams mParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT
        );

        for (int i = 0, s = pics.length; i < s; i++) {
            ImageView v = new ImageView(this);
            v.setLayoutParams(mParams);
            v.setScaleType(ImageView.ScaleType.FIT_XY);
            v.setImageResource(pics[i]);
            if (i == s - 1) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        goActivity(v);
                    }
                });
            }
            mViews.add(v);
        }

        mViewPager.setAdapter(mViewPagerAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setCurrentPoint(position);
                currentIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 设置当前Page View
     *
     * @param position
     */
    private void setCurrentView(int position) {
        if (position < 0 || position >= pics.length) {
            return;
        }
        mViewPager.setCurrentItem(position);
    }

    /**
     * 设置当前Point View
     *
     * @param position
     */
    private void setCurrentPoint(int position) {
        if (position < 0 || position >= pics.length || currentIndex == position) {
            return;
        }
        mPointViews[position].setEnabled(false);
        mPointViews[currentIndex].setEnabled(true);
    }


    private void initPagerView() {
        mViews = new ArrayList<View>();
        mViewPagerAdapter = new ViewPagerAdapter(mViews);
    }

    private PointImageViewOnClickHandler pointImageViewOnClickHandler = new PointImageViewOnClickHandler();

    class PointImageViewOnClickHandler implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            int position = (Integer) v.getTag();
            setCurrentView(position);
            setCurrentPoint(position);
            currentIndex = position;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                HeathFoodApplication.ActivityCollector.finishAllActivity();
                Toast.makeText(this, R.string.info_exit, Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
        return true;
    }

    //进入主界面
    public void goActivity(View view) {
        if (!HeathFoodApplication.isNetworkAvailable()) {
            Toast.makeText(this, R.string.info_network_not_available, Toast.LENGTH_LONG).show();
            this.finish();
        } else {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMax(mMaxProgressValue);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mProgressDialog.setMessage(getString(R.string.info_food_loading));
            mProgressDialog.show();
            mProgressDialog.setProgress(mProgressValue > 0 ? mProgressValue : 0);
            mHandler.sendEmptyMessageDelayed(DialogWhat, 100);
            backstageLoadData();
        }
    }

    private void backstageLoadData() {
        final Message message = Message.obtain(mHandler);
        message.what = LoadingWhat;
        final Bundle bundle = new Bundle();
        bundle.putLong(Constants.CLASSIFY_ID, Constants.CLASSIFY_ROOT);
        BackgroundTaskExecutor.doTask(bundle, message, new BackgroundTasks.LoadFoodClass(mApiClient));
    }
}
